package com.enjoyor.soa.traffic.server.efoms.dubbo.manage;

import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;

import com.alibaba.dubbo.config.annotation.Service;
import com.enjoyor.soa.traffic.api.dto.efoms.RepairsInfoDto;
import com.enjoyor.soa.traffic.api.ubms.dto.DeviceInfoDto;
import com.enjoyor.soa.traffic.core.efoms.domain.FileInfo;
import com.enjoyor.soa.traffic.core.efoms.domain.RepairsInfo;
import com.enjoyor.soa.traffic.core.efoms.domain.WorkordersInfo;
import com.enjoyor.soa.traffic.core.efoms.domain.WorkordersRecordInfo;
import com.enjoyor.soa.traffic.core.efoms.enums.EnumDicPublic;
import com.enjoyor.soa.traffic.core.efoms.service.IRepairsInfoService;
import com.enjoyor.soa.traffic.core.efoms.service.IWorkordersInfoService;
import com.enjoyor.soa.traffic.core.efoms.service.IWorkordersRecordService;
import com.enjoyor.soa.traffic.frame.support.util.DomainUtil;
import com.enjoyor.soa.traffic.process.vo.ProcessVo;
import com.enjoyor.soa.traffic.server.efoms.dubbo.invoke.DubboProcessServiceInvoke;
import com.enjoyor.soa.traffic.server.efoms.dubbo.invoke.DubboUbmsServiceInvoke;
import com.enjoyor.soa.traffic.server.efoms.dubbo.listener.MessagePushClient;
import com.enjoyor.soa.traffic.server.efoms.helper.ObjectSwitchHelper;
import com.enjoyor.soa.traffic.util.enums.EnumAppCode;
import com.enjoyor.soa.traffic.util.helper.LoggerHelper;
import com.enjoyor.soa.traffic.util.helper.ReflectHelper;
import com.enjoyor.soa.traffic.util.helper.ResultHelper;
import com.enjoyor.soa.traffic.util.helper.TimeHelper;
import com.enjoyor.soa.traffic.util.pojo.Page;
import com.enjoyor.soa.traffic.util.pojo.ResultPojo;

@Service
public class ManageRepairsInfoService {

	@Autowired
	private IRepairsInfoService repairsInfoService;

	@Autowired
	private IWorkordersInfoService workordersInfoService;
	
	@Autowired
	private IWorkordersRecordService workordersRecordService;
	
    @Autowired 
    private ManageDevStatusInfoService manageDevStatusInfoService;

	@Autowired
	private DubboUbmsServiceInvoke dubboUbmsServiceInvoke;

	@Autowired
	private DubboProcessServiceInvoke dubboProcessServiceInvoke;
	
	@Autowired
	private MessagePushClient messagePushClient;
	
	public ResultPojo select(String repairsId) {
		// TODO Auto-generated method stub
		try {
			RepairsInfo repairsInfo = repairsInfoService.select(repairsId);
			return ResultHelper.getResult(ReflectHelper.beanToBean(repairsInfo, RepairsInfoDto.class));
		} catch (Exception e) {
            LoggerHelper.LOG.error(e);
            return ResultHelper.getResult(e);
        }
	}

	public ResultPojo selectList(String repairsId, String repStatusCode, String devTypeCode, String devAreaCode,
			String devId, String devName, String key,String press, String repDeptIds, String startTime, String endTime) {
		// TODO Auto-generated method stub
		try {
			List<RepairsInfo> repairsInfoList = repairsInfoService.selectList(repairsId, repStatusCode, devTypeCode,
					devAreaCode, devId, devName,key,press, repDeptIds, startTime, endTime);
			return ResultHelper.getResult(ReflectHelper.listToList(repairsInfoList, RepairsInfoDto.class));
		} catch (Exception e) {
            LoggerHelper.LOG.error(e);
            return ResultHelper.getResult(e);
        }
	}

	public ResultPojo selectPage(Page page, String repairsId, String repStatusCode, String devTypeCode,
			String devAreaCode, String key,String press, String repDeptIds, String startTime,
			String endTime) {
		// TODO Auto-generated method stub
		try {
			return ResultHelper.getResult(repairsInfoService.selectPage(page, repairsId, repStatusCode, devTypeCode, devAreaCode,
					key,press,repDeptIds, startTime, endTime));
		} catch (Exception e) {
            LoggerHelper.LOG.error(e);
            return ResultHelper.getResult(e);
        }
	}
	
	/***
	 * 报修单增加
	 * repairsInfoDto:报修单对象；
	 * userName:操作人名称；
	 */
	public ResultPojo insert(RepairsInfoDto repairsInfoDto, String userName){
		ResultPojo result = new ResultPojo();
		try {
			RepairsInfo repairsInfo = ReflectHelper.beanToBean(repairsInfoDto, RepairsInfo.class);
			List<FileInfo> fileList = DomainUtil.merge2ListJson(repairsInfoDto.getFileList(), FileInfo.class);
			repairsInfo.setFileList(fileList);
			
			// TODO Auto-generated method stub
			String devId = repairsInfoDto.getDevId();
	    	String devTypeCode = repairsInfoDto.getDevTypeCode();
	    	if(null != devId && !"".equals(devId) && null != devTypeCode && !"".equals(devTypeCode)) {
	    		//设备重复检验
	    		String flagCheck = this.devCheck(devTypeCode, devId, userName);
	    		if("1".equals(flagCheck)) {
	    			return ResultHelper.getResult("该设备处于报修中, 自动产生催办记录！");
	    		}else if("2".equals(flagCheck)){
	    			return ResultHelper.getResult("该设备处于维修中, 自动产生催办记录！");
	    		}
	    		
	    		//获取设备基础信息
	    		ResultPojo resultPojo = dubboUbmsServiceInvoke.getDevInfoList(devId, devTypeCode);
	    		List<DeviceInfoDto> listDeviceInfoDto = (List<DeviceInfoDto>) resultPojo.getResultList();
	    		if (null != listDeviceInfoDto && listDeviceInfoDto.size() > 0) {
	    			DeviceInfoDto deviceInfoDto = listDeviceInfoDto.get(0);
	    			repairsInfo = ObjectSwitchHelper.UbmsDeviceToRepairsInfo(deviceInfoDto, repairsInfo);
	    		}
	    	}
	    	result = repairsInfoService.insert(repairsInfo, userName);
	    	//修改设备状态数据--报修中
			manageDevStatusInfoService.saveDevStatusInfo(
					repairsInfo.getDevCategoryCode(),repairsInfo.getDevCategoryName(),
					repairsInfo.getDevTypeCode(), repairsInfo.getDevTypeName(),
					repairsInfo.getDevId(), repairsInfo.getDevName(), 
					EnumDicPublic.DEV_REP_STATUS_REPAIRING.getKey(), 
					EnumDicPublic.DEV_REP_STATUS_REPAIRING.getValue(), 
					null, null, userName);
			//DeviceStatusInfo deviceStatusInfo = ObjectSwitchHelper.RepairsToDevStatusInfo(repairsInfo);
			//devStatusInfoService.insertDevStatusInfo(deviceStatusInfo, userName);
			//统计待审核数据
			messagePushClient.repMsgApply();
			//需审核报修单提醒；
			messagePushClient.getRepSubmitPushMessage();
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			return ResultHelper.getResult(e);
		}
		return result; 
	}
	
	public ResultPojo edit(RepairsInfoDto repairsInfoDto, String userName) {
		// TODO Auto-generated method stub
		try {
			List<FileInfo> fileList = DomainUtil.merge2ListJson(repairsInfoDto.getFileList(), FileInfo.class);
			RepairsInfo repairsInfo = ReflectHelper.beanToBean(repairsInfoDto, RepairsInfo.class);
			repairsInfo.setFileList(fileList);
			ResultPojo result = repairsInfoService.edit(repairsInfo, userName);
			return result;
		} catch (Exception e) {
            LoggerHelper.LOG.error(e);
            return ResultHelper.getResult(e);
        }
	}

	public ResultPojo delete(String repairsId, String userName) {
		try {
			ResultPojo result = repairsInfoService.delete(repairsId, userName);
			return result;
		} catch (Exception e) {
            LoggerHelper.LOG.error(e);
            return ResultHelper.getResult(e);
        }
	}
	
	/***
	 * 报修单审核
	 * @param repairsId 报修单编号；
	 * @param userName 操作人
	 * @param isPass 审核是否通过（0：不通过，1通过）
	 * @param operExplain 审核详情；
	 * @return 报修单编号；
	 */
	public ResultPojo audit(String repairsId, String userName, String isPass, String operExplain){
		// TODO Auto-generated method stub
		String resultId = repairsId;
		repairsInfoService.audit(repairsId, userName, isPass, operExplain);
		try {
			RepairsInfo repairsInfo = repairsInfoService.select(repairsId);
			if ("1".equals(isPass) && repairsInfo!=null) {//若为审核操作，则在审核通过之后生成工单；
					WorkordersInfo workordersInfo = ObjectSwitchHelper.repairsToWorkorders(repairsInfo);
					String workordersId = "W" + TimeHelper.getUniqueString();
					//启动流程引擎
					String processId = dubboProcessServiceInvoke.startOrdersAProcess(workordersId);
					
					String workordersStatusCode = "";
			    	ProcessVo processVo = dubboProcessServiceInvoke.submitProcess(workordersId, null, 
			    			EnumDicPublic.ORD_OPER_SUBMIT.getKey());
			    	if(processVo.getResult()) {
			        	workordersStatusCode = processVo.getTaskDefinitionKey();
			    	}else {
			    		return ResultHelper.getResult(EnumAppCode.WORK_FLOW_ERROR, "流程引擎执行错误！");
			    	}
			    	workordersInfo.setWorkordersId(workordersId);
			    	workordersInfo.setProcessId(processId);
			    	workordersInfo.setWorkordersStatusCode(workordersStatusCode);
			    	resultId = workordersInfoService.insertWorkordersInfo(workordersInfo, userName);
			    	
			    	//修改设备状态数据--维修中、故障
			    	manageDevStatusInfoService.saveDevStatusInfo(
			    			repairsInfo.getDevCategoryCode(),repairsInfo.getDevCategoryName(),
							repairsInfo.getDevTypeCode(), repairsInfo.getDevTypeName(),
							repairsInfo.getDevId(), repairsInfo.getDevName(), 
							EnumDicPublic.DEV_REP_STATUS_MAINTAINING.getKey(), 
							EnumDicPublic.DEV_REP_STATUS_MAINTAINING.getValue(),
							EnumDicPublic.DEVICE_STATUS_FAILURE.getKey(), 
							EnumDicPublic.DEVICE_STATUS_FAILURE.getValue(), userName);
			}else if("0".equals(isPass) && repairsInfo!=null) {
				manageDevStatusInfoService.saveDevStatusInfo(
						repairsInfo.getDevCategoryCode(),repairsInfo.getDevCategoryName(),
						repairsInfo.getDevTypeCode(), repairsInfo.getDevTypeName(),
						repairsInfo.getDevId(), repairsInfo.getDevName(), 
						EnumDicPublic.DEV_REP_STATUS_USEING.getKey(), 
						EnumDicPublic.DEV_REP_STATUS_USEING.getValue(), 
						null, null, userName);
			}
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			return ResultHelper.getResult(e);
		}
		//统计待审核数据
		messagePushClient.repMsgApply();
		return ResultHelper.getResult(resultId);
	}
	
	public ResultPojo cancel(String repairsId, String userName, String operExplain, String operReasonCode,String operReasonName) {
		try {
			ResultPojo result = repairsInfoService.cancel(repairsId, userName, operExplain, operReasonCode, operReasonName);
			//修改设备状态数据--使用中
			RepairsInfo repairsInfo = repairsInfoService.select(repairsId);
			if(null != repairsInfo) {
				manageDevStatusInfoService.saveDevStatusInfo(
						repairsInfo.getDevCategoryCode(),repairsInfo.getDevCategoryName(),
						repairsInfo.getDevTypeCode(), repairsInfo.getDevTypeName(),
						repairsInfo.getDevId(), repairsInfo.getDevName(), 
						EnumDicPublic.DEV_REP_STATUS_USEING.getKey(), 
						EnumDicPublic.DEV_REP_STATUS_USEING.getValue(), 
						null, null, userName);
			}
			//统计待审核数据
			messagePushClient.repMsgApply();
			//统计催办数据
			messagePushClient.repMsgPress();
			return result;
		} catch (Exception e) {
            LoggerHelper.LOG.error(e);
            return ResultHelper.getResult(e);
        }
	}

	public ResultPojo press(String repairsId, String userName, String operExplain) {
		try {
			ResultPojo result = repairsInfoService.press(repairsId, userName, operExplain);
			//统计催办数据
			messagePushClient.repMsgPress();
			//报修单催办提醒
			messagePushClient.getRepPressPushMessage();
			return result;
		} catch (Exception e) {
            LoggerHelper.LOG.error(e);
            return ResultHelper.getResult(e);
        }
	}
	
	/***
	 * 设备状态校验
	 * devTypeCode:设备类型编号；
	 * devId:设备编号；
	 */
	public ResultPojo devRepeatCheck(String devTypeCode, String devId) {
		try {
			String result = "设备状态正常";
			List<RepairsInfo> repairsInfoList = repairsInfoService.selectList(null, EnumDicPublic.REP_WAITCHECK.getKey(), 
					devTypeCode, null, devId, null, null,null, null, null, null);
			if(null != repairsInfoList && repairsInfoList.size() > 0) {
				return ResultHelper.getResult(EnumAppCode.PARAM_NAME_EXISTS, "该设备处于报修中状态！");
			}
			List<WorkordersInfo> workordersInfoList = workordersInfoService.selectWorkordersInfoList(
					null, devTypeCode, devId);
			if(null != workordersInfoList && workordersInfoList.size() > 0) {
				return ResultHelper.getResult(EnumAppCode.PARAM_NAME_EXISTS, "该设备处于维修中状态！");
			}
			return ResultHelper.getResult(result);
		} catch (Exception e) {
            LoggerHelper.LOG.error(e);
            return ResultHelper.getResult(e);
        }
	}
	
	public ResultPojo getOperationCount(String startTime,String endTime) {
		try {
			Map<String, Object> resultMap = repairsInfoService.getOperationCount(startTime,endTime);
			return ResultHelper.getResult(resultMap);
		} catch (Exception e) {
            LoggerHelper.LOG.error(e);
            return ResultHelper.getResult(e);
        }
	}
	
	/**
	 * 设备报修、维修时，设备校验
	 *@param devTypeCode:设备类型编号；
	 *@param devId:设备编号；
	 *@param userName:操作用户；
	 *@return 0为无重复，1为报修重复，2为维修工单重复
	 */
	public String devCheck(String devTypeCode, String devId, String userName) {
		String resultFlag = "0";
		//报修数据重复校验
		List<RepairsInfo> repairsInfoList = repairsInfoService.selectList(null, EnumDicPublic.REP_WAITCHECK.getKey(), 
				devTypeCode, null, devId, null,null, null, null, null, null);
		if(null != repairsInfoList && repairsInfoList.size() > 0) {
			repairsInfoService.press(repairsInfoList.get(0).getRepairsId(), userName, "该设备处于报修中,自动产生催办记录！");
			messagePushClient.repMsgPress();
			resultFlag = "1";
			return resultFlag;
		}
		//维修数据重复校验
		List<WorkordersInfo> workordersInfoList = workordersInfoService.selectWorkordersInfoList(
				null, devTypeCode, devId);
		if(null != workordersInfoList && workordersInfoList.size() > 0) {
			WorkordersRecordInfo workordersRecord = new WorkordersRecordInfo();
			workordersRecord.setWorkordersId(workordersInfoList.get(0).getWorkordersId());
			workordersRecord.setOperTypeCode(EnumDicPublic.ORD_OPER_PRESS.getKey());
			workordersRecord.setOperTypeName(EnumDicPublic.ORD_OPER_PRESS.getValue());
			workordersRecord.setOperExplain("该设备处于维修中,自动产生催办记录！");
			workordersRecord.setOperPerson(userName);
    		workordersRecordService.insertWorkordersRecord(workordersRecord, null,  null, userName);
    		messagePushClient.ordMsgPress();
    		resultFlag = "2";
			return resultFlag;
		}
		return resultFlag;
	}
}
